package com.ycyoes.test.hollis.datastructure.tree;

public class Trie {
    private Trie[] children;
    private boolean isWord;

    public Trie() {
        this.isWord = false;
        this.children = new Trie[26];
    }

    public void insert(String word) {
        Trie next = this;
        for (char c : word.toCharArray()) {
            if (next.children[c - 'a'] == null) {
                next.children[c - 'a'] = new Trie();
            }
            next = next.children[c - 'a'];
        }
        next.isWord = true;
    }

    public boolean search(String word) {
        Trie next = this;
        for(char c : word.toCharArray()) {
            if (next.children[c - 'a'] == null) {
                return false;
            }
            next = next.children[c - 'a'];
        }
        return next.isWord;
    }

    public boolean startsWith(String prefix) {
        Trie next = this;
        for (char c : prefix.toCharArray()) {
            if (next.children[c - 'a'] == null) {
                return false;
            }
            next = next.children[c - 'a'];
        }
        return true;
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("test");
        trie.insert("apple");
        trie.insert("table");
        System.out.println(trie.search("hello"));
        System.out.println(trie.search("test"));
    }
}
